package edu.jmu.springmvc;

import java.awt.Color;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

@Component("userListPdf")
public class UserListPdfView extends AbstractPdfView {

	@Override
	protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setHeader("Content-Disposition", "inline;filename="+
			new String("用户列表".getBytes(),"iso8859-1"));
		List<User1> user1List = (List<User1>)model.get("user1List");
		Table table = new Table(3);
		table.setWidth(80);
		table.setBorder(1);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
		table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
		/*1.使用中文字体*/
		BaseFont cnBaseFont = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",false);
		Font cnFont = new Font(cnBaseFont,10,Font.NORMAL,Color.BLUE);
		table.addCell(buildFontCell("姓", cnFont));//对于中文字符需使用中文字段构造Cell对象
		table.addCell(buildFontCell("名", cnFont));
		table.addCell(buildFontCell("生日", cnFont));
		for (User1 user1 : user1List) {
			table.addCell(user1.getFirstName());//英文字符可以直接添加到Cell中
			table.addCell(buildFontCell(user1.getLastName(), cnFont));
			String createDate = DateFormatUtils.format(new Date(),	"yyyy-MM-dd");
			table.addCell(createDate);
		}
		document.add(table);
	}
	private Cell buildFontCell(String content, Font font) throws RuntimeException{
		Phrase phrase = new Phrase(content,font);
		try {
			return new Cell(phrase);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
